import {action, observable} from 'mobx'
import {axiosFetch, handleResp} from "../../util/common/http";
import {Toast} from "antd-mobile";
import history from "../../util/router/history";
import {testPass} from "../../util/common/kit";
import {Base64} from "js-base64";

export class UserPasswordStore {
	@observable userId: number|null = null;
	// 提交按钮状态(1:禁用 2:可用 3:操作中)
	@observable submitBtnStatus: number = 2;

	@observable password: string|null = null;
	@observable passwordConfirm: string|null = null;

	/**
	 * 获取登录人基本信息
	 */
	@action initUserInfo = async (userId: number) => {
		this.userId = userId;
	};

	/**
	 * 更新密码
	 * @param value
	 */
	@action changeFirstPassword = (value: string) => {
			this.password = value;
	};

	/**
	 * 更新确认输入的密码
	 * @param value
	 */
	@action changeConfirmPassword = (value: string) => {
		this.passwordConfirm = value;
	};

	/**
	 * 请求后台,修改用户登陆密码
	 */
	@action updateUserPassword = async () => {
		if (!this.userId) {
			return;
		}
		if (!this.password) {
			Toast.fail("新密码必填!", 1.5);
			return false;
		}
		if (!testPass(this.password)) {
			return false;
		}
		if (!this.passwordConfirm) {
			Toast.fail("确认新密码必填!", 1.5);
			return false;
		}
		if (this.password !== this.passwordConfirm) {
			Toast.fail("您输入的两次密码不一致!", 1.5);
			return false;
		}
		this.submitBtnStatus = 3;
		const fetchResp = await axiosFetch("/user/password/update", {
			method: 'PUT',
			data: {
				userId: this.userId,
				userPassword: Base64.encode(this.password)
			}
		});

		this.submitBtnStatus = 2;
		if (handleResp(fetchResp)) {
			Toast.success("密码修改成功");
			history.goBack();
		}
	};

}

export default new UserPasswordStore();
